package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.provider.model.dto.life.alertToExcelDto;
import com.csun.cmny.provider.model.vo.device.DmcDeviceAlertLifeRoomVo;
import com.csun.cmny.provider.model.vo.life.DmcDeviceByRoom;
import com.csun.cmny.provider.service.DmcDeviceAlertService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.util.PublicUtil;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/api")
@RestController
public class toExcel {
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DmcDeviceAlertService dmcDeviceAlertService;

    /*life导出报警信息*/

    //@GetMapping(value = "toExcel/queryDeviceAlertLifeRoomToExcel")
    @RequestMapping("/downEST")
    public void queryDeviceAlertLifeRoomToExcel(alertToExcelDto alertToExcelDto, HttpServletResponse response) throws IOException {

        List<Long> deviceIds = new ArrayList<>();

        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setGroupId(1077l);

        List<DmcDeviceByRoom> dmcDeviceByRooms = dmcDeviceService.selectDeviceByRoomId(alertToExcelDto.getRoomId(),loginAuthDto.getGroupId());
        for (DmcDeviceByRoom dmcDeviceByRoom : dmcDeviceByRooms) {
            deviceIds.add(dmcDeviceByRoom.getDeviceId());
        }

        if(PublicUtil.isNotEmpty(deviceIds)){
            List<DmcDeviceAlertLifeRoomVo> dmcDeviceAlertLifeRoomVos = dmcDeviceAlertService.queryDeviceAlertLifeRoomAndTime(deviceIds, loginAuthDto.getGroupId(),alertToExcelDto.getStartTime(),alertToExcelDto.getEndTime());
            for (DmcDeviceAlertLifeRoomVo dmcDeviceAlertLifeRoomVo : dmcDeviceAlertLifeRoomVos) {
                if (dmcDeviceAlertLifeRoomVo.getIsHandle()==0){
                    dmcDeviceAlertLifeRoomVo.setUpdateTime(null);
                }
            }

            Workbook workbook = DefaultExcelBuilder.of(DmcDeviceAlertLifeRoomVo.class)
                    .build(dmcDeviceAlertLifeRoomVos);

            AttachmentExportUtil.export(workbook,"id为"+alertToExcelDto.getRoomId()+"号房间的报警信息",response);

        }

    }
}
